<template>
  <div class="container">
    <!-- 图片展示区域 -->
    <div class="display-area">
      <h3>当前图片</h3>
      <div class="image-container">
        <img v-if="currentImage" :src="currentImage" class="display-image" />
        <el-icon v-else class="no-image"><Picture /></el-icon>
      </div>
    </div>

    <!-- 操作区域 -->
    <div class="action-area">
      <!-- 上传组件 -->
      <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :headers="headers"
              name="file"
              v-show="isUploading">
        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>

      <!-- 操作按钮 -->
      <div class="button-group">
        <el-button type="primary" @click="handleUploadClick" :disabled="isUploading">
          {{ isUploading ? '取消上传' : '上传图片' }}
        </el-button>
        <el-button type="warning" @click="handleChangeClick">更改图片</el-button>
        <el-button type="danger" @click="handleDeleteClick" :disabled="!currentImage">
          删除图片
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
  import { ref } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { Plus, Picture } from '@element-plus/icons-vue'
  import axios from 'axios'

  // 状态变量
  const uploadUrl = 'http://localhost:8080/upload/images'
  const imageUrl = ref('')
  const currentImage = ref('') // 当前展示的图片
  const isUploading = ref(false) // 是否显示上传组件
  const headers = {
    // 如果需要认证，在这里添加
    // 'Authorization': 'Bearer ' + localStorage.getItem('token')
  }

  // 上传成功的回调
  const handleAvatarSuccess = (response) => {
    console.log('上传响应：', response)
    imageUrl.value = response
    currentImage.value = response
    isUploading.value = false
    ElMessage.success('上传成功')
  }

  // 上传前的验证
  const beforeAvatarUpload = (file) => {
    const acceptTypes = ['image/jpeg', 'image/png', 'image/gif']
    const isValidType = acceptTypes.includes(file.type)
    const isLt2M = file.size / 1024 / 1024 < 2

    if (!isValidType) {
      ElMessage.error('只能上传 JPG/PNG/GIF 格式的图片!')
      return false
    }
    if (!isLt2M) {
      ElMessage.error('图片大小不能超过 2MB!')
      return false
    }

    return true
  }

  // 处理上传按钮点击
  const handleUploadClick = () => {
    isUploading.value = !isUploading.value
  }

  // 处理更改按钮点击
  const handleChangeClick = () => {
    isUploading.value = true
  }

  // 处理删除按钮点击
  const handleDeleteClick = async () => {
    try {
      await ElMessageBox.confirm('确定要删除这张图片吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })

      if (currentImage.value) {
        const fileName = currentImage.value.split('/').pop()
        await axios.get(`http://localhost:8080/upload/delete`, {
          params: { fileName }
        })
        currentImage.value = ''
        imageUrl.value = ''
        ElMessage.success('删除成功')
      }
    } catch (error) {
      if (error !== 'cancel') {
        console.error('删除失败：', error)
        ElMessage.error('删除失败：' + (error.message || '未知错误'))
      }
    }
  }

  // 暴露方法给父组件
  defineExpose({
    currentImage,
    getImageUrl: () => currentImage.value
  })
</script>

<style scoped>
  .container {
    padding: 20px;
    max-width: 800px;
    margin: 0 auto;
  }

  .display-area {
    margin-bottom: 30px;
    text-align: center;
  }

  .image-container {
    width: 300px;
    height: 300px;
    margin: 0 auto;
    border: 2px dashed #dcdfe6;
    border-radius: 8px;
    display: flex;
    justify-content: center;
    align-items: center;
    overflow: hidden;
  }

  .display-image {
    max-width: 100%;
    max-height: 100%;
    object-fit: contain;
  }

  .no-image {
    font-size: 48px;
    color: #909399;
  }

  .action-area {
    text-align: center;
  }

  .avatar-uploader {
    margin-bottom: 20px;
  }

  .avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
    object-fit: cover;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
    margin: 0 auto;
  }

  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
    line-height: 178px;
  }

  .button-group {
    display: flex;
    justify-content: center;
    gap: 16px;
  }
</style>